package vista;

import controlador.DBManager;
import java.io.File;
import javax.swing.JOptionPane;

/**
 * Clase para crear una base de datos, donde se le solicita al usuario un nombre
 *
 * @author Mª Luz García Rodríguez
 * @author Luis Massó Saiz
 */
public class JFrameCrearBd extends javax.swing.JFrame {

    JIntTablasBd jFTabla;
    MdiPrueba mymdi;

    public void setMymdi(MdiPrueba mymdi) {
        this.mymdi = mymdi;
    }

    /**
     * Constructor JFrameCrearBd
     */
    public JFrameCrearBd() {
        initComponents();

        //mymdi = new MdiPrueba();
        jFTabla = new JIntTablasBd();
        this.setLocationRelativeTo(null);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jTNombreBD = new javax.swing.JTextField();
        jBCancelar = new javax.swing.JButton();
        jBCrear = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Crear Base Datos");
        setResizable(false);

        jLabel1.setText("Nombre de la Base de Datos");

        jBCancelar.setText("Cancelar");
        jBCancelar.setPreferredSize(new java.awt.Dimension(130, 40));
        jBCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBCancelarActionPerformed(evt);
            }
        });

        jBCrear.setText("Crear");
        jBCrear.setPreferredSize(new java.awt.Dimension(130, 40));
        jBCrear.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBCrearActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jTNombreBD)
                    .addComponent(jLabel1, javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addComponent(jBCrear, javax.swing.GroupLayout.DEFAULT_SIZE, 142, Short.MAX_VALUE)
                        .addGap(18, 18, 18)
                        .addComponent(jBCancelar, javax.swing.GroupLayout.DEFAULT_SIZE, 143, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(26, 26, 26)
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jTNombreBD, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jBCancelar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jBCrear, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(34, 34, 34))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    /**
     * Método que cierra el formulario JFrameCrearBD
     *
     * @param evt
     */
    private void jBCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBCancelarActionPerformed
        this.dispose();
    }//GEN-LAST:event_jBCancelarActionPerformed

    /**
     * Método que crea la base de datos según el nombre que haya introducido el
     * usuario
     *
     * @param evt
     */
    private void jBCrearActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBCrearActionPerformed
        String ArchivoBd = jTNombreBD.getText();
        if (!ArchivoBd.contains(".sqlite")) {
            ArchivoBd = ArchivoBd + ".sqlite";
        }
        if (new File(ArchivoBd).exists()) {
            int respuesta = JOptionPane.showConfirmDialog(null, "El archivo " + ArchivoBd
                    + " ya existe.\n¿Quiere conectarse a él?", "Archivo existente", JOptionPane.OK_CANCEL_OPTION);
            if (respuesta == JOptionPane.OK_OPTION) {
                try {
                    DBManager myDB = new DBManager(ArchivoBd);
                    mymdi.conectarBd(myDB);
                    this.jTNombreBD.setText("");
                    this.dispose();
                } catch (Exception ex) {
                    JOptionPane.showMessageDialog(null, "Error creando la Base de Datos", "Creando Bd", JOptionPane.ERROR_MESSAGE);
                }
            }
        } else {
            try {
                DBManager myDB = new DBManager(ArchivoBd);
                JOptionPane.showMessageDialog(null, "Base de datos " + ArchivoBd + " creada correctamente", "Creando BD", JOptionPane.PLAIN_MESSAGE);
                jTNombreBD.setText("");
                this.setVisible(false);

                //jFTabla.setVisible(true);
                jFTabla.setBdManager(myDB);
                mymdi.setTablas(jFTabla);
            } catch (Exception ex) {
                JOptionPane.showMessageDialog(null, "Error accediendo a la Base de datos", "Abriendo BD", JOptionPane.ERROR_MESSAGE);
            }
        }
    }//GEN-LAST:event_jBCrearActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(JFrameCrearBd.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(JFrameCrearBd.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(JFrameCrearBd.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(JFrameCrearBd.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new JFrameCrearBd().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jBCancelar;
    private javax.swing.JButton jBCrear;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JTextField jTNombreBD;
    // End of variables declaration//GEN-END:variables
}
